package com.qianyu.core.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qianyu.core.entity.bean.MoneyWater;
import com.qianyu.core.entity.bean.OrderPay;
import com.qianyu.core.entity.bean.User;
import com.qianyu.core.entity.dto.OrderPayDto;
import com.qianyu.core.helper.LoginHelper;
import com.qianyu.core.mapper.OrderPayMapper;
import com.qianyu.core.service.MoneyWaterService;
import com.qianyu.core.service.OrderPayService;
import com.qianyu.core.service.UserService;
import com.qianyu.core.util.IpUtil;
import com.qianyu.core.util.TimeUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class OrderPayServiceImpl extends ServiceImpl<OrderPayMapper, OrderPay> implements OrderPayService {


    private final UserService userService;

    private final MoneyWaterService moneyWaterService;

    @Override
    public Boolean saveOrder(OrderPayDto.OrderPaySaveDto dto, HttpServletRequest request) {
        OrderPay orderPay = BeanUtil.copyProperties(dto, OrderPay.class);
        orderPay.setUserId(LoginHelper.getUserId());
        orderPay.setOrderSn("CZUSDT" + TimeUtil.unixTime());
        orderPay.setIp(IpUtil.getIpAddr(request));
        orderPay.setStatus(0);
        return save(orderPay);
    }

    @Override
    public Page<OrderPay> pageOrderPay(OrderPayDto.OrderPayPageDto dto, Long userId) {
        List<User> users = userService.list();
        Map<Long, String> map = users.stream().collect(Collectors.toMap(User::getId, User::getNickname));
        Page<OrderPay> page = new Page<>(dto.getPageNum(), dto.getPageSize());
        LambdaQueryWrapper<OrderPay> wrapper = Wrappers.lambdaQuery();
        if (ObjUtil.isNotEmpty(dto.getStartTime())) {
            wrapper.ge(OrderPay::getCreateTime, dto.getStartTime());
        }
        if (ObjUtil.isNotEmpty(dto.getEndTime())) {
            wrapper.le(OrderPay::getCreateTime, TimeUtil.toDayLastTime(dto.getEndTime()));
        }
        if (dto.getStatus() != null) {
            wrapper.eq(OrderPay::getStatus, dto.getStatus());
        }
        if (userId != null) {
            wrapper.eq(OrderPay::getUserId, userId);
        }

        IPage<OrderPay> payIPage = baseMapper.selectPage(page, wrapper);
        payIPage.getRecords().forEach(p -> {
            p.setNickname(map.get(p.getUserId()));
            if (p.getAuditId() != null) {
                p.setAuditName(map.get(p.getAuditId()));
            }
        });
        return (Page<OrderPay>) payIPage;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean checkPayOrder(OrderPayDto.OrderPayAuditDto dto) {
        OrderPay orderPay = getById(dto.getId());
        BeanUtil.copyProperties(dto,orderPay);
        orderPay.setAuditTime(new Date());
        orderPay.setAuditId(LoginHelper.getUserId());
        if(dto.getStatus() == 2){
            User user = userService.getById(orderPay.getUserId());
            user.setMoney(user.getMoney().add(dto.getPayAmount()));
            userService.updateById(user);
            //新增钱包流水
            MoneyWater moneyWater = new MoneyWater(){{
                setUserId(user.getId());
                setBalance(dto.getPayAmount());
                setAfterBalance(user.getMoney());
                setRemark("充值");
                setType(1);
                setIsIncome(1);
            }};
            moneyWaterService.save(moneyWater);
        }
        return updateById(orderPay);
    }
}
